package stx.com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import stx.com.entity.TDiary;
import stx.com.entity.TUser;
import stx.com.util.Constans;

@Repository
public class DiaryDaoImp implements DiaryDao {

	@Resource
	
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public boolean addDiary(TDiary diary) {
		String sql="insert into tbl_diary values(seq_diary.nextval,?,?,?,?,?)";
		Object[] args=new Object[]{diary.getDatetime(),diary.getTitle(),diary.getContent(),diary.getAccounts(),diary.getCname()};
		int num=jdbcTemplate.update(sql, args);
		return num==Constans.REYURN_NUM;
	}

	@Override
	public List<TDiary> lookDiary(TDiary diary) {
		String sql="select * from tbl_diary where useraccounts=?";
		Object[] args=new Object[]{diary.getAccounts()};
		List<TDiary> diarys=jdbcTemplate.query(sql, args,new MyRowMapper());
		return diarys; 
				
	}
	
	@Override
	public TDiary look(TDiary diary){
		System.out.println(diary.getJnumber());
		String sql="select * from tbl_diary where jnumber=?";
		Object[] args=new Object[]{diary.getJnumber()};
		List<TDiary> diarys=jdbcTemplate.query(sql, args,new MyRowMapper());
		return diarys.get(0);
	}


	@Override
	public boolean updateDiary(TDiary diary) {
		String sql="update tbl_diary set title=?,content=?,cname=? where jnumber=?";
		Object[] args=new Object[]{diary.getTitle(),diary.getContent(),diary.getCname(),diary.getJnumber()};
		boolean a= jdbcTemplate.update(sql, args)==Constans.REYURN_NUM;
		System.out.println(a);
		return a;
	}

	@Override
	public boolean deleteDiary(TDiary diary) {
		String sql="delete from tbl_diary where junmber=?";
		Object[] args=new Object[]{diary.getJnumber()};
		return jdbcTemplate.update(sql, args)==Constans.REYURN_NUM;
	}
	
	
	private class MyRowMapper implements RowMapper {
		@Override
		public TDiary mapRow(ResultSet rs, int arg1) throws SQLException {
			TDiary diary = new TDiary();
			TUser user=new TUser();
			diary.setAccounts(rs.getString("useraccounts"));
			diary.setDatetime(rs.getString("datetime"));
			diary.setTitle(rs.getString("title"));
			diary.setContent(rs.getString("content"));
			diary.setCname(rs.getString("cname"));
			diary.setJnumber(rs.getInt("jnumber"));
//			user.setUseraccounts(rs.getString("useraccounts"));
			return diary;
		}
	}

}
